<template>
    <div class="container">
        <h1>天气查询</h1>
        <div class="search-box">
            <el-cascader placeholder="请选择" :options="addressBook" @change="handleChange" />
            <button @click="fetchWeather" :disabled="!selectedCity">
                {{ loading ? '查询中...' : '查询' }}
            </button>
        </div>
        <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
        <div v-if="weatherInfoVisible" class="weather-info">
            <div class="weather-details">
                <div class="weather-item">
                    <h3>天气现象</h3>
                    <p>{{ weatherData.weather }}</p>
                </div>
                <div class="weather-item">
                    <h3>实时温度</h3>
                    <p>{{ weatherData.temperature }}°C</p>
                </div>
                <div class="weather-item">
                    <h3>空气湿度</h3>
                    <p>{{ weatherData.humidity }}%</p>
                </div>
                <div class="weather-item">
                    <h3>风向</h3>
                    <p>{{ weatherData.windDirection }}</p>
                </div>
                <div class="weather-item">
                    <h3>风力级别</h3>
                    <p>{{ weatherData.windPower }} 级</p>
                </div>
                <div class="weather-item">
                    <h3>数据发布时间</h3>
                    <p>{{ formattedReportTime }}</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {ref, computed} from 'vue'
// 高德地图API密钥（替换为你的实际密钥）
const API_KEY = '1ca359eecec334858899b7f3df7bc084'

const selectedProvince = ref('')
const selectedCity = ref('')
const selectedDistrict = ref('')
const weatherData = ref({})
const errorMessage = ref('')
const loading = ref(false)
const weatherInfoVisible = ref(false)
const currentLocation = ref('')

const addressBook = require("@/data/address.json")
const handleChange = (value) => {
  selectedProvince.value = value[0]
  selectedCity.value = value[1]
  selectedDistrict.value = value[2]
}

// 计算属性
const formattedReportTime = computed(() => {
  return weatherData.value.reporttime
      ? new Date(weatherData.value.reporttime).toLocaleString('zh-CN')
      : '未知'
})

async function fetchWeather(area) {
  loading.value = true
  errorMessage.value = ''
  weatherInfoVisible.value = false

  try {
    const response = await fetch(
        `https://restapi.amap.com/v3/weather/weatherInfo?city=${selectedDistrict.value}&key=${API_KEY}`
    )
    const data = await response.json()

    if (data.status === '1' && data.lives?.length) {
      updateWeatherData(data.lives[0])
      currentLocation.value = data.lives[0].city || area
      weatherInfoVisible.value = true
    } else {
      throw new Error('未找到天气信息')
    }
  } catch (error) {
    showError(error.message)
  } finally {
    loading.value = false
  }
}

function updateWeatherData(data) {
  weatherData.value = {
    weather: data.weather || '未知',
    temperature: data.temperature || '--',
    humidity: data.humidity || '--',
    windDirection: data.winddirection || '未知',
    windPower: data.windpower || '--',
    reporttime: data.reporttime || ''
  }
}

function showError(message) {
  errorMessage.value = message
  weatherInfoVisible.value = false
}

</script>

<style scoped>
/* 保持原有样式不变 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'Microsoft YaHei', sans-serif;
  background: linear-gradient(to bottom, #87CEEB, #1E90FF);
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  width: 100%;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  gap: 10px;
  margin-bottom: 20px;
}

.location-select {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
}

button {
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.weather-info {
  padding: 15px;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  margin-top: 20px;
}

.weather-info h2 {
  color: #1E90FF;
  text-align: center;
  margin-bottom: 15px;
}

.weather-details {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  padding: 10px;
}

.weather-item {
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.weather-item h3 {
  color: #333;
  font-size: 14px;
  margin-bottom: 8px;
}

.weather-item p {
  color: #666;
  font-size: 16px;
  font-weight: bold;
}

.error-message {
  color: red;
  text-align: center;
  margin-top: 10px;
}
</style>